home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _2984d035cfb099f5a833d6fe545f7bc1 < prev    next >
Encoding:
Text File  |  2002-05-01  |  35.1 KB  |  1,154 lines

  1. # $Id: UserAgent.pm,v 2.1 2001/12/11 21:11:29 gisle Exp $
  2.  
  3. package LWP::UserAgent;
  4. use strict;
  5.  
  6. =head1 NAME
  7.  
  8. LWP::UserAgent - A WWW UserAgent class
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  require LWP::UserAgent;
  13.  my $ua = LWP::UserAgent->new(env_proxy => 1,
  14.                               keep_alive => 1,
  15.                               timeout => 30,
  16.                              );
  17.  
  18.  $response = $ua->get('http://search.cpan.org/');
  19.  
  20.  # or:
  21.  
  22.  $request = HTTP::Request->new('GET', 'http://search.cpan.org/');
  23.   # and then one of these:
  24.  $response = $ua->request($request); # or
  25.  $response = $ua->request($request, '/tmp/sss'); # or
  26.  $response = $ua->request($request, \&callback, 4096);
  27.  
  28.  sub callback { my($data, $response, $protocol) = @_; .... }
  29.  
  30. =head1 DESCRIPTION
  31.  
  32. The C<LWP::UserAgent> is a class implementing a World-Wide Web
  33. user agent in Perl. It brings together the HTTP::Request,
  34. HTTP::Response and the LWP::Protocol classes that form the rest of the
  35. core of libwww-perl library. For simple uses this class can be used
  36. directly to dispatch WWW requests, alternatively it can be subclassed
  37. for application-specific behaviour.
  38.  
  39. In normal use the application creates a C<LWP::UserAgent> object, and then
  40. configures it with values for timeouts, proxies, name, etc. It then
  41. creates an instance of C<HTTP::Request> for the request that
  42. needs to be performed. This request is then passed to one of the UserAgent's
  43. request() methods, which dispatches it using the relevant protocol,
  44. and returns a C<HTTP::Response> object.
  45.  
  46. There are convenience methods for sending the most common request
  47. types; get(), head() and post().
  48.  
  49. The basic approach of the library is to use HTTP style communication
  50. for all protocol schemes, i.e. you even receive an C<HTTP::Response>
  51. object for gopher or ftp requests.  In order to achieve even more
  52. similarity to HTTP style communications, gopher menus and file
  53. directories are converted to HTML documents.
  54.  
  55. The send_request(), simple_request() and request() methods can process
  56. the content of the response in one of three ways: in core, into a
  57. file, or into repeated calls to a subroutine.  You choose which one by
  58. the kind of value passed as the second argument.
  59.  
  60. The in core variant simply stores the content in a scalar 'content'
  61. attribute of the response object and is suitable for small HTML
  62. replies that might need further parsing.  This variant is used if the
  63. second argument is missing (or is undef).
  64.  
  65. The filename variant requires a scalar containing a filename as the
  66. second argument to the request method and is suitable for large WWW
  67. objects which need to be written directly to the file without
  68. requiring large amounts of memory. In this case the response object
  69. returned from the request method will have an empty content attribute.
  70. If the request fails, then the content might not be empty, and the
  71. file will be untouched.
  72.  
  73. The subroutine variant requires a reference to callback routine as the
  74. second argument to the request method and it can also take an optional
  75. chuck size as the third argument.  This variant can be used to
  76. construct "pipe-lined" processing, where processing of received
  77. chuncks can begin before the complete data has arrived.  The callback
  78. function is called with 3 arguments: the data received this time, a
  79. reference to the response object and a reference to the protocol
  80. object.  The response object returned from the request method will
  81. have empty content.  If the request fails, then the the callback
  82. routine is not called, and the response->content might not be empty.
  83.  
  84. The request can be aborted by calling die() in the callback
  85. routine.  The die message will be available as the "X-Died" special
  86. response header field.
  87.  
  88. The library also allows you to use a subroutine reference as
  89. content in the request object.  This subroutine should return the
  90. content (possibly in pieces) when called.  It should return an empty
  91. string when there is no more content.
  92.  
  93. =head1 METHODS
  94.  
  95. The following methods are available:
  96.  
  97. =over 4
  98.  
  99. =cut
  100.  
  101.  
  102. use vars qw(@ISA $VERSION);
  103.  
  104. require LWP::MemberMixin;
  105. @ISA = qw(LWP::MemberMixin);
  106. $VERSION = sprintf("%d.%03d", q$Revision: 2.1 $ =~ /(\d+)\.(\d+)/);
  107.  
  108. use HTTP::Request ();
  109. use HTTP::Response ();
  110. use HTTP::Date ();
  111.  
  112. use LWP ();
  113. use LWP::Debug ();
  114. use LWP::Protocol ();
  115.  
  116. use Carp ();
  117.  
  118. if ($ENV{PERL_LWP_USE_HTTP_10}) {
  119.     require LWP::Protocol::http10;
  120.     LWP::Protocol::implementor('http', 'LWP::Protocol::http10');
  121.     eval {
  122.         require LWP::Protocol::https10;
  123.         LWP::Protocol::implementor('https', 'LWP::Protocol::https10');
  124.     };
  125. }
  126.  
  127. =item $ua = LWP::UserAgent->new( %options );
  128.  
  129. This class method constructs a new C<LWP::UserAgent> object and
  130. returns a reference to it.
  131.  
  132. Key/value pair arguments may be provided to set up the initial state
  133. of the user agent.  The following options correspond to attribute
  134. methods described below:
  135.  
  136.    KEY                     DEFAULT
  137.    -----------             --------------------
  138.    agent                   "libwww-perl/#.##"
  139.    from                    undef
  140.    timeout                 180
  141.    use_eval                1
  142.    parse_head              1
  143.    max_size                undef
  144.    cookie_jar              undef
  145.    conn_cache              undef
  146.    protocols_allowed       undef
  147.    protocols_forbidden     undef
  148.    requests_redirectable   ['GET', 'HEAD']
  149.  
  150. The followings option are also accepted: If the C<env_proxy> option is
  151. passed in an has a TRUE value, then proxy settings are read from
  152. environment variables.  If the C<keep_alive> option is passed in, then
  153. a C<LWP::ConnCache> is set up (see conn_cache() method below).  The
  154. keep_alive value is a number and is passed on as the total_capacity
  155. for the connection cache.  The C<keep_alive> option also has the
  156. effect of loading and enabling the new experimental HTTP/1.1 protocol
  157. module.
  158.  
  159. =cut
  160.  
  161. sub new
  162. {
  163.     my($class, %cnf) = @_;
  164.     LWP::Debug::trace('()');
  165.  
  166.     my $agent = delete $cnf{agent};
  167.     $agent = $class->_agent unless defined $agent;
  168.  
  169.     my $from  = delete $cnf{from};
  170.     my $timeout = delete $cnf{timeout};
  171.     $timeout = 3*60 unless defined $timeout;
  172.     my $use_eval = delete $cnf{use_eval};
  173.     $use_eval = 1 unless defined $use_eval;
  174.     my $parse_head = delete $cnf{parse_head};
  175.     $parse_head = 1 unless defined $parse_head;
  176.     my $max_size = delete $cnf{max_size};
  177.     my $env_proxy = delete $cnf{env_proxy};
  178.  
  179.     my $cookie_jar = delete $cnf{cookie_jar};
  180.     my $conn_cache = delete $cnf{conn_cache};
  181.     my $keep_alive = delete $cnf{keep_alive};
  182.     
  183.     Carp::croak("Can't mix conn_cache and keep_alive")
  184.       if $conn_cache && $keep_alive;
  185.  
  186.  
  187.     my $protocols_allowed   = delete $cnf{protocols_allowed};
  188.     my $protocols_forbidden = delete $cnf{protocols_forbidden};
  189.     
  190.     my $requests_redirectable = delete $cnf{requests_redirectable};
  191.     $requests_redirectable = ['GET', 'HEAD']
  192.       unless defined $requests_redirectable;
  193.  
  194.     # Actually ""s are just as good as 0's, but for concision we'll just say:
  195.     Carp::croak("protocols_allowed has to be an arrayref or 0, not \"$protocols_allowed\"!")
  196.       if $protocols_allowed and ref($protocols_allowed) ne 'ARRAY';
  197.     Carp::croak("protocols_forbidden has to be an arrayref or 0, not \"$protocols_forbidden\"!")
  198.       if $protocols_forbidden and ref($protocols_forbidden) ne 'ARRAY';
  199.     Carp::croak("requests_redirectable has to be an arrayref or 0, not \"$requests_redirectable\"!")
  200.       if $requests_redirectable and ref($requests_redirectable) ne 'ARRAY';
  201.  
  202.  
  203.     if (%cnf && $^W) {
  204.     Carp::carp("Unrecognized LWP::UserAgent options: @{[sort keys %cnf]}");
  205.     }
  206.  
  207.     my $self = bless {
  208.               from        => $from,
  209.               timeout     => $timeout,
  210.               use_eval    => $use_eval,
  211.               parse_head  => $parse_head,
  212.               max_size    => $max_size,
  213.               proxy       => undef,
  214.               no_proxy    => [],
  215.                       protocols_allowed => $protocols_allowed,
  216.                       protocols_forbidden => $protocols_forbidden,
  217.                       requests_redirectable => $requests_redirectable,
  218.              }, $class;
  219.  
  220.     $self->agent($agent) if $agent;
  221.     $self->cookie_jar($cookie_jar) if $cookie_jar;
  222.     $self->env_proxy if $env_proxy;
  223.  
  224.     $self->protocols_allowed(  $protocols_allowed  ) if $protocols_allowed;
  225.     $self->protocols_forbidden($protocols_forbidden) if $protocols_forbidden;
  226.  
  227.     if ($keep_alive) {
  228.     $conn_cache ||= { total_capacity => $keep_alive };
  229.     }
  230.     $self->conn_cache($conn_cache) if $conn_cache;
  231.  
  232.     return $self;
  233. }
  234.  
  235.  
  236. # private method.  check sanity of given $request
  237. sub _request_sanity_check {
  238.     my($self, $request) = @_;
  239.     # some sanity checking
  240.     if (defined $request) {
  241.     if (ref $request) {
  242.         Carp::croak("You need a request object, not a " . ref($request) . " object")
  243.           if ref($request) eq 'ARRAY' or ref($request) eq 'HASH' or
  244.          !$request->can('method') or !$request->can('uri');
  245.     }
  246.     else {
  247.         Carp::croak("You need a request object, not '$request'");
  248.     }
  249.     }
  250.     else {
  251.         Carp::croak("No request object passed in");
  252.     }
  253. }
  254.  
  255.  
  256. =item $ua->send_request($request, $arg [, $size])
  257.  
  258. This method dispatches a single WWW request on behalf of a user, and
  259. returns the response received.  The request is sent off unmodified,
  260. without passing it through C<prepare_request()>.
  261.  
  262. The C<$request> should be a reference to a C<HTTP::Request> object
  263. with values defined for at least the method() and uri() attributes.
  264.  
  265. If C<$arg> is a scalar it is taken as a filename where the content of
  266. the response is stored.
  267.  
  268. If C<$arg> is a reference to a subroutine, then this routine is called
  269. as chunks of the content is received.  An optional C<$size> argument
  270. is taken as a hint for an appropriate chunk size.
  271.  
  272. If C<$arg> is omitted, then the content is stored in the response
  273. object itself.
  274.  
  275. =cut
  276.  
  277. sub send_request
  278. {
  279.     my($self, $request, $arg, $size) = @_;
  280.     $self->_request_sanity_check($request);
  281.  
  282.     my($method, $url) = ($request->method, $request->uri);
  283.  
  284.     local($SIG{__DIE__});  # protect agains user defined die handlers
  285.  
  286.     # Check that we have a METHOD and a URL first
  287.     return _new_response($request, &HTTP::Status::RC_BAD_REQUEST, "Method missing")
  288.     unless $method;
  289.     return _new_response($request, &HTTP::Status::RC_BAD_REQUEST, "URL missing")
  290.     unless $url;
  291.     return _new_response($request, &HTTP::Status::RC_BAD_REQUEST, "URL must be absolute")
  292.     unless $url->scheme;
  293.  
  294.     LWP::Debug::trace("$method $url");
  295.  
  296.     # Locate protocol to use
  297.     my $scheme = '';
  298.     my $proxy = $self->_need_proxy($url);
  299.     if (defined $proxy) {
  300.     $scheme = $proxy->scheme;
  301.     } else {
  302.     $scheme = $url->scheme;
  303.     }
  304.  
  305.     my $protocol;
  306.  
  307.     {
  308.       # Honor object-specific restrictions by forcing protocol objects
  309.       #  into class LWP::Protocol::nogo.
  310.       my $x;
  311.       if($x       = $self->protocols_allowed) {
  312.         if(grep $_ eq $scheme, @$x) {
  313.           LWP::Debug::trace("$scheme URLs are among $self\'s allowed protocols (@$x)");
  314.         } else {
  315.           LWP::Debug::trace("$scheme URLs aren't among $self\'s allowed protocols (@$x)");
  316.           require LWP::Protocol::nogo;
  317.           $protocol = LWP::Protocol::nogo->new;
  318.         }
  319.       } elsif ($x = $self->protocols_forbidden) {
  320.         if(grep $_ eq $scheme, @$x) {
  321.           LWP::Debug::trace("$scheme URLs are among $self\'s forbidden protocols (@$x)");
  322.           require LWP::Protocol::nogo;
  323.           $protocol = LWP::Protocol::nogo->new;
  324.         } else {
  325.           LWP::Debug::trace("$scheme URLs aren't among $self\'s forbidden protocols (@$x)");
  326.         }
  327.       }
  328.       # else fall thru and create the protocol object normally
  329.     }
  330.  
  331.     unless($protocol) {
  332.       $protocol = eval { LWP::Protocol::create($scheme, $self) };
  333.       if ($@) {
  334.     $@ =~ s/ at .* line \d+.*//s;  # remove file/line number
  335.     return _new_response($request, &HTTP::Status::RC_NOT_IMPLEMENTED, $@);
  336.       }
  337.     }
  338.  
  339.     # Extract fields that will be used below
  340.     my ($timeout, $cookie_jar, $use_eval, $parse_head, $max_size) =
  341.       @{$self}{qw(timeout cookie_jar use_eval parse_head max_size)};
  342.  
  343.     my $response;
  344.     if ($use_eval) {
  345.     # we eval, and turn dies into responses below
  346.     eval {
  347.         $response = $protocol->request($request, $proxy,
  348.                        $arg, $size, $timeout);
  349.     };
  350.     if ($@) {
  351.         $@ =~ s/ at .* line \d+.*//s;  # remove file/line number
  352.         $response =
  353.           HTTP::Response->new(&HTTP::Status::RC_INTERNAL_SERVER_ERROR,
  354.                   $@);
  355.     }
  356.     } else {
  357.     $response = $protocol->request($request, $proxy,
  358.                        $arg, $size, $timeout);
  359.     # XXX: Should we die unless $response->is_success ???
  360.     }
  361.  
  362.     $response->request($request);  # record request for reference
  363.     $cookie_jar->extract_cookies($response) if $cookie_jar;
  364.     $response->header("Client-Date" => HTTP::Date::time2str(time));
  365.     return $response;
  366. }
  367.  
  368.  
  369. =item $ua->prepare_request($request)
  370.  
  371. This method modifies given C<HTTP::Request> object by setting up
  372. various headers based on the attributes of the $ua.  The headers
  373. affected are; C<User-Agent>, C<From>, C<Range> and C<Cookie>.
  374.  
  375. The return value is the $request object passed in.
  376.  
  377. =cut
  378.  
  379. sub prepare_request
  380. {
  381.     my($self, $request) = @_;
  382.     $self->_request_sanity_check($request);
  383.  
  384.     # Extract fields that will be used below
  385.     my ($agent, $from, $cookie_jar, $max_size) =
  386.       @{$self}{qw(agent from cookie_jar max_size)};
  387.  
  388.     # Set User-Agent and From headers if they are defined
  389.     $request->init_header('User-Agent' => $agent) if $agent;
  390.     $request->init_header('From' => $from) if $from;
  391.     if (defined $max_size) {
  392.     my $last = $max_size - 1;
  393.     $last = 0 if $last < 0;  # there is no way to actually request no content
  394.     $request->init_header('Range' => "bytes=0-$last");
  395.     }
  396.     $cookie_jar->add_cookie_header($request) if $cookie_jar;
  397.  
  398.     return($request);
  399. }
  400.  
  401.  
  402. =item $ua->simple_request($request, [$arg [, $size]])
  403.  
  404. This method dispatches a single WWW request on behalf of a user, and
  405. returns the response received.  If differs from C<send_request()> by
  406. automatically calling the C<prepare_request()> method before the
  407. request is sent.
  408.  
  409. The arguments are the same as for C<send_request()>.
  410.  
  411. =cut
  412.  
  413. sub simple_request
  414. {
  415.     my($self, $request, $arg, $size) = @_;
  416.     $self->_request_sanity_check($request);
  417.     my $new_request = $self->prepare_request($request);
  418.     return($self->send_request($new_request, $arg, $size));
  419. }
  420.  
  421.  
  422. =item $ua->request($request, $arg [, $size])
  423.  
  424. Process a request, including redirects and security.  This method may
  425. actually send several different simple requests.
  426.  
  427. The arguments are the same as for C<send_request()> and
  428. C<simple_request()>.
  429.  
  430. =cut
  431.  
  432. sub request
  433. {
  434.     my($self, $request, $arg, $size, $previous) = @_;
  435.  
  436.     LWP::Debug::trace('()');
  437.  
  438.     my $response = $self->simple_request($request, $arg, $size);
  439.  
  440.     my $code = $response->code;
  441.     $response->previous($previous) if defined $previous;
  442.  
  443.     LWP::Debug::debug('Simple response: ' .
  444.               (HTTP::Status::status_message($code) ||
  445.                "Unknown code $code"));
  446.  
  447.     if ($code == &HTTP::Status::RC_MOVED_PERMANENTLY or
  448.     $code == &HTTP::Status::RC_MOVED_TEMPORARILY) {
  449.  
  450.     # Make a copy of the request and initialize it with the new URI
  451.     my $referral = $request->clone;
  452.  
  453.     # And then we update the URL based on the Location:-header.
  454.     my($referral_uri) = $response->header('Location');
  455.     {
  456.         # Some servers erroneously return a relative URL for redirects,
  457.         # so make it absolute if it not already is.
  458.         local $URI::ABS_ALLOW_RELATIVE_SCHEME = 1;
  459.         my $base = $response->base;
  460.         $referral_uri = $HTTP::URI_CLASS->new($referral_uri, $base)
  461.                     ->abs($base);
  462.     }
  463.  
  464.     $referral->url($referral_uri);
  465.     $referral->remove_header('Host', 'Cookie');
  466.  
  467.     return $response unless $self->redirect_ok($referral);
  468.  
  469.     # Check for loop in the redirects
  470.     my $count = 0;
  471.     my $r = $response;
  472.     while ($r) {
  473.         if (++$count > 13 ||
  474.                 $r->request->url->as_string eq $referral_uri->as_string) {
  475.         $response->header("Client-Warning" =>
  476.                   "Redirect loop detected");
  477.         return $response;
  478.         }
  479.         $r = $r->previous;
  480.     }
  481.  
  482.     return $self->request($referral, $arg, $size, $response);
  483.  
  484.     } elsif ($code == &HTTP::Status::RC_UNAUTHORIZED ||
  485.          $code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED
  486.         )
  487.     {
  488.     my $proxy = ($code == &HTTP::Status::RC_PROXY_AUTHENTICATION_REQUIRED);
  489.     my $ch_header = $proxy ?  "Proxy-Authenticate" : "WWW-Authenticate";
  490.     my @challenge = $response->header($ch_header);
  491.     unless (@challenge) {
  492.         $response->header("Client-Warning" => 
  493.                   "Missing Authenticate header");
  494.         return $response;
  495.     }
  496.  
  497.     require HTTP::Headers::Util;
  498.     CHALLENGE: for my $challenge (@challenge) {
  499.         $challenge =~ tr/,/;/;  # "," is used to separate auth-params!!
  500.         ($challenge) = HTTP::Headers::Util::split_header_words($challenge);
  501.         my $scheme = lc(shift(@$challenge));
  502.         shift(@$challenge); # no value
  503.         $challenge = { @$challenge };  # make rest into a hash
  504.         for (keys %$challenge) {       # make sure all keys are lower case
  505.         $challenge->{lc $_} = delete $challenge->{$_};
  506.         }
  507.  
  508.         unless ($scheme =~ /^([a-z]+(?:-[a-z]+)*)$/) {
  509.         $response->header("Client-Warning" => 
  510.                   "Bad authentication scheme '$scheme'");
  511.         return $response;
  512.         }
  513.         $scheme = $1;  # untainted now
  514.         my $class = "LWP::Authen::\u$scheme";
  515.         $class =~ s/-/_/g;
  516.  
  517.         no strict 'refs';
  518.         unless (%{"$class\::"}) {
  519.         # try to load it
  520.         eval "require $class";
  521.         if ($@) {
  522.             if ($@ =~ /^Can\'t locate/) {
  523.             $response->header("Client-Warning" =>
  524.                       "Unsupported authentication scheme '$scheme'");
  525.             } else {
  526.             $response->header("Client-Warning" => $@);
  527.             }
  528.             next CHALLENGE;
  529.         }
  530.         }
  531.         return $class->authenticate($self, $proxy, $challenge, $response,
  532.                     $request, $arg, $size);
  533.     }
  534.     return $response;
  535.     }
  536.     return $response;
  537. }
  538.  
  539. #---------------------------------------------------------------------------
  540. # Now the shortcuts...
  541.  
  542. =item $ua->get($url, Header => Value,...);
  543.  
  544. This is a shortcut for C<$ua-E<gt>request(HTTP::Request::Common::GET(
  545. $url, Header =E<gt> Value,... ))>.  See
  546. L<HTTP::Request::Common|HTTP::Request::Common>.
  547.  
  548. =item $ua->post($url, \%formref, Header => Value,...);
  549.  
  550. This is a shortcut for C<$ua-E<gt>request( HTTP::Request::Common::POST(
  551. $url, \%formref, Header =E<gt> Value,... ))>.  Note that the form
  552. reference is optional, and can be either a hashref (C<\%formdata> or C<{
  553. 'key1' => 'val2', 'key2' => 'val2', ...
  554. }>) or an arrayref (C<\@formdata> or
  555. C<['key1' => 'val2', 'key2' => 'val2', ...]>).  See
  556. L<HTTP::Request::Common|HTTP::Request::Common>.
  557.  
  558. =item $ua->head($url, Header => Value,...);
  559.  
  560. This is a shortcut for C<$ua-E<gt>request( HTTP::Request::Common::HEAD(
  561. $url, Header =E<gt> Value,... ))>.  See
  562. L<HTTP::Request::Common|HTTP::Request::Common>.
  563.  
  564. =item $ua->put($url, Header => Value,...);
  565.  
  566. This is a shortcut for C<$ua-E<gt>request( HTTP::Request::Common::PUT(
  567. $url, Header =E<gt> Value,... ))>.  See
  568. L<HTTP::Request::Common|HTTP::Request::Common>.
  569.  
  570. =cut
  571.  
  572. sub get {
  573.   require HTTP::Request::Common;
  574.   return shift->request( HTTP::Request::Common::GET( @_ ) );
  575. }
  576.  
  577. sub post {
  578.   require HTTP::Request::Common;
  579.   return shift->request( HTTP::Request::Common::POST( @_ ) );
  580. }
  581.  
  582. sub head {
  583.   require HTTP::Request::Common;
  584.   return shift->request( HTTP::Request::Common::HEAD( @_ ) );
  585. }
  586.  
  587. sub put {
  588.   require HTTP::Request::Common;
  589.   return shift->request( HTTP::Request::Common::PUT( @_ ) );
  590. }
  591.  
  592.  
  593. #---------------------------------------------------------------------------
  594. # This whole allow/forbid thing is based on man 1 at's way of doing things.
  595.  
  596. =item $ua->protocols_allowed( );  # to read
  597.  
  598. =item $ua->protocols_allowed( \@protocols ); # to set
  599.  
  600. This reads (or sets) this user-agent's list of procotols that
  601. C<$ua-E<gt>request> and C<$ua-E<gt>simple_request> will exclusively
  602. allow.
  603.  
  604. For example: C<$ua-E<gt>protocols_allowed( [ 'http', 'https'] );>
  605. means that this user agent will I<allow only> those protocols,
  606. and attempts to use this user-agent to access URLs with any other
  607. schemes (like "ftp://...") will result in a 500 error.
  608.  
  609. To delete the list, call: 
  610. C<$ua-E<gt>protocols_allowed(undef)>
  611.  
  612. By default, an object has neither a protocols_allowed list, nor
  613. a protocols_forbidden list.
  614.  
  615. Note that having a protocols_allowed
  616. list causes any protocols_forbidden list to be ignored.
  617.  
  618. =item $ua->protocols_forbidden( );  # to read
  619.  
  620. =item $ua->protocols_forbidden( \@protocols ); # to set
  621.  
  622. This reads (or sets) this user-agent's list of procotols that
  623. C<$ua-E<gt>request> and C<$ua-E<gt>simple_request> will I<not> allow.
  624.  
  625. For example: C<$ua-E<gt>protocols_forbidden( [ 'file', 'mailto'] );>
  626. means that this user-agent will I<not> allow those protocols, and
  627. attempts to use this user-agent to access URLs with those schemes
  628. will result in a 500 error.
  629.  
  630. To delete the list, call: 
  631. C<$ua-E<gt>protocols_forbidden(undef)>
  632.  
  633. =item $ua->is_protocol_supported($scheme)
  634.  
  635. You can use this method to test whether this user-agent object supports the
  636. specified C<scheme>.  (The C<scheme> might be a string (like 'http' or
  637. 'ftp') or it might be an URI object reference.)
  638.  
  639. Whether a scheme is supported, is determined by $ua's protocols_allowed or
  640. protocols_forbidden lists (if any), and by the capabilities
  641. of LWP.  I.e., this will return TRUE only if LWP supports this protocol
  642. I<and> it's permitted for this particular object.
  643.  
  644. =cut
  645.  
  646. sub is_protocol_supported
  647. {
  648.     my($self, $scheme) = @_;
  649.     if (ref $scheme) {
  650.     # assume we got a reference to an URI object
  651.     $scheme = $scheme->scheme;
  652.     } else {
  653.     Carp::croak("Illegal scheme '$scheme' passed to is_protocol_supported")
  654.         if $scheme =~ /\W/;
  655.     $scheme = lc $scheme;
  656.     }
  657.  
  658.     my $x;
  659.     if(ref($self) and $x       = $self->protocols_allowed) {
  660.       return 0 unless grep $_ eq $scheme, @$x;
  661.     } elsif (ref($self) and $x = $self->protocols_forbidden) {
  662.       return 0 if grep $_ eq $scheme, @$x;
  663.     }
  664.  
  665.     local($SIG{__DIE__});  # protect agains user defined die handlers
  666.     $x = LWP::Protocol::implementor($scheme);
  667.     return 1 if $x and $x ne 'LWP::Protocol::nogo';
  668.     return 0;
  669. }
  670.  
  671. #---------------------------------------------------------------------------
  672.  
  673. =item $ua->requests_redirectable( );  # to read
  674.  
  675. =item $ua->requests_redirectable( \@requests );  # to set
  676.  
  677. This reads or sets the object's list of request names that 
  678. C<$ua-E<gt>redirect_ok(...)> will allow redirection for.  By
  679. default, this is C<['GET', 'HEAD']>, as per RFC 2068.  To
  680. change to include 'POST', consider:
  681.  
  682.    push @{ $ua->requests_redirectable }, 'POST';
  683.  
  684. =cut
  685.  
  686. sub protocols_allowed      { shift->_elem('protocols_allowed'    , @_) }
  687. sub protocols_forbidden    { shift->_elem('protocols_forbidden'  , @_) }
  688. sub requests_redirectable  { shift->_elem('requests_redirectable', @_) }
  689.  
  690. #---------------------------------------------------------------------------
  691.  
  692. =item $ua->redirect_ok($prospective_request)
  693.  
  694. This method is called by request() before it tries to follow a
  695. redirection to the request in $prospective_request.  This
  696. should return a true value if this redirection is
  697. permissible.
  698.  
  699. The default implementation will return FALSE unless the method
  700. is in the object's C<requests_redirectable> list,
  701. FALSE if the proposed redirection is to a "file://..."
  702. URL, and TRUE otherwise.
  703.  
  704. Subclasses might want to override this.
  705.  
  706. (This method's behavior in previous versions was simply to return
  707. TRUE for anything except POST requests).
  708.  
  709. =cut
  710.  
  711. sub redirect_ok
  712. {
  713.     # RFC 2068, section 10.3.2 and 10.3.3 say:
  714.     #  If the 30[12] status code is received in response to a request other
  715.     #  than GET or HEAD, the user agent MUST NOT automatically redirect the
  716.     #  request unless it can be confirmed by the user, since this might
  717.     #  change the conditions under which the request was issued.
  718.  
  719.     # Note that this routine used to be just:
  720.     #  return 0 if $_[1]->method eq "POST";  return 1;
  721.  
  722.     my($self, $request) = @_;
  723.     my $method = $request->method;
  724.     return 0 unless grep $_ eq $method,
  725.       @{ $self->requests_redirectable || [] };
  726.     
  727.     if($request->url->scheme eq 'file') {
  728.       LWP::Debug::trace("Can't redirect to a file:// URL!");
  729.       return 0;
  730.     }
  731.     
  732.     # Otherwise it's apparently okay...
  733.     return 1;
  734. }
  735.  
  736.  
  737. =item $ua->credentials($netloc, $realm, $uname, $pass)
  738.  
  739. Set the user name and password to be used for a realm.  It is often more
  740. useful to specialize the get_basic_credentials() method instead.
  741.  
  742. =cut
  743.  
  744. sub credentials
  745. {
  746.     my($self, $netloc, $realm, $uid, $pass) = @_;
  747.     @{ $self->{'basic_authentication'}{$netloc}{$realm} } = ($uid, $pass);
  748. }
  749.  
  750.  
  751. =item $ua->get_basic_credentials($realm, $uri, [$proxy])
  752.  
  753. This is called by request() to retrieve credentials for a Realm
  754. protected by Basic Authentication or Digest Authentication.
  755.  
  756. Should return username and password in a list.  Return undef to abort
  757. the authentication resolution atempts.
  758.  
  759. This implementation simply checks a set of pre-stored member
  760. variables. Subclasses can override this method to e.g. ask the user
  761. for a username/password.  An example of this can be found in
  762. C<lwp-request> program distributed with this library.
  763.  
  764. =cut
  765.  
  766. sub get_basic_credentials
  767. {
  768.     my($self, $realm, $uri, $proxy) = @_;
  769.     return if $proxy;
  770.  
  771.     my $host_port = $uri->host_port;
  772.     if (exists $self->{'basic_authentication'}{$host_port}{$realm}) {
  773.     return @{ $self->{'basic_authentication'}{$host_port}{$realm} };
  774.     }
  775.  
  776.     return (undef, undef);
  777. }
  778.  
  779.  
  780. =item $ua->agent([$product_id])
  781.  
  782. Get/set the product token that is used to identify the user agent on
  783. the network.  The agent value is sent as the "User-Agent" header in
  784. the requests.  The default is the string returned by the _agent()
  785. method (see below).
  786.  
  787. If the $product_id ends with space then the C<_agent> string is
  788. appended to it.
  789.  
  790. The user agent string should be one or more simple product identifiers
  791. with an optional version number separated by the "/" character.
  792. Examples are:
  793.  
  794.   $ua->agent('Checkbot/0.4 ' . $ua->_agent);
  795.   $ua->agent('Checkbot/0.4 ');    # same as above
  796.   $ua->agent('Mozilla/5.0');
  797.   $ua->agent("");                 # don't identify
  798.  
  799. =item $ua->_agent
  800.  
  801. Returns the default agent identifier.  This is a string of the form
  802. "libwww-perl/#.##", where "#.##" is substitued with the version numer
  803. of this library.
  804.  
  805. =cut
  806.  
  807. sub agent {
  808.     my $self = shift;
  809.     my $old = $self->{agent};
  810.     if (@_) {
  811.     my $agent = shift;
  812.     $agent .= $self->_agent if $agent && $agent =~ /\s+$/;
  813.     $self->{agent} = $agent;
  814.     }
  815.     $old;
  816. }
  817.  
  818. sub _agent     { "libwww-perl/$LWP::VERSION" }
  819.  
  820.  
  821. =item $ua->from([$email_address])
  822.  
  823. Get/set the Internet e-mail address for the human user who controls
  824. the requesting user agent.  The address should be machine-usable, as
  825. defined in RFC 822.  The from value is send as the "From" header in
  826. the requests.  Example:
  827.  
  828.   $ua->from('gaas@cpan.org');
  829.  
  830. The default is to not send a "From" header.
  831.  
  832. =item $ua->timeout([$secs])
  833.  
  834. Get/set the timeout value in seconds. The default timeout() value is
  835. 180 seconds, i.e. 3 minutes.
  836.  
  837. =item $ua->cookie_jar([$cookie_jar_obj])
  838.  
  839. Get/set the cookie jar object to use.  The only requirement is that
  840. the cookie jar object must implement the extract_cookies($request) and
  841. add_cookie_header($response) methods.  These methods will then be
  842. invoked by the user agent as requests are sent and responses are
  843. received.  Normally this will be a C<HTTP::Cookies> object or some
  844. subclass.
  845.  
  846. The default is to have no cookie_jar, i.e. never automatically add
  847. "Cookie" headers to the requests.
  848.  
  849. Shortcut: If a reference to a plain hash is passed in as the
  850. $cookie_jar_object, then it is replaced with an instance of
  851. C<HTTP::Cookies> that is initalized based on the hash.  This form also
  852. automatically loads the C<HTTP::Cookies> module.  It means that:
  853.  
  854.   $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });
  855.  
  856. is really just a shortcut for:
  857.  
  858.   require HTTP::Cookies;
  859.   $ua->cookie_jar(HTTP::Cookies->new(file => "$ENV{HOME}/.cookies.txt"));
  860.  
  861. =item $ua->conn_cache([$cache_obj])
  862.  
  863. Get/set the I<LWP::ConnCache> object to use.
  864.  
  865. =item $ua->parse_head([$boolean])
  866.  
  867. Get/set a value indicating wether we should initialize response
  868. headers from the E<lt>head> section of HTML documents. The default is
  869. TRUE.  Do not turn this off, unless you know what you are doing.
  870.  
  871. =item $ua->max_size([$bytes])
  872.  
  873. Get/set the size limit for response content.  The default is C<undef>,
  874. which means that there is no limit.  If the returned response content
  875. is only partial, because the size limit was exceeded, then a
  876. "Client-Aborted" header will be added to the response.
  877.  
  878. =cut
  879.  
  880. sub timeout    { shift->_elem('timeout',   @_); }
  881. sub from       { shift->_elem('from',      @_); }
  882. sub parse_head { shift->_elem('parse_head',@_); }
  883. sub max_size   { shift->_elem('max_size',  @_); }
  884.  
  885. sub cookie_jar {
  886.     my $self = shift;
  887.     my $old = $self->{cookie_jar};
  888.     if (@_) {
  889.     my $jar = shift;
  890.     if (ref($jar) eq "HASH") {
  891.         require HTTP::Cookies;
  892.         $jar = HTTP::Cookies->new(%$jar);
  893.     }
  894.     $self->{cookie_jar} = $jar;
  895.     }
  896.     $old;
  897. }
  898.  
  899. sub conn_cache {
  900.     my $self = shift;
  901.     my $old = $self->{conn_cache};
  902.     if (@_) {
  903.     my $cache = shift;
  904.     if (ref($cache) eq "HASH") {
  905.         require LWP::ConnCache;
  906.         $cache = LWP::ConnCache->new(%$cache);
  907.     }
  908.     $self->{conn_cache} = $cache;
  909.     }
  910.     $old;
  911. }
  912.  
  913. # depreciated
  914. sub use_eval   { shift->_elem('use_eval',  @_); }
  915. sub use_alarm
  916. {
  917.     Carp::carp("LWP::UserAgent->use_alarm(BOOL) is a no-op")
  918.     if @_ > 1 && $^W;
  919.     "";
  920. }
  921.  
  922.  
  923. =item $ua->clone;
  924.  
  925. Returns a copy of the LWP::UserAgent object
  926.  
  927. =cut
  928.  
  929.  
  930. sub clone
  931. {
  932.     my $self = shift;
  933.     my $copy = bless { %$self }, ref $self;  # copy most fields
  934.  
  935.     # elements that are references must be handled in a special way
  936.     $copy->{'proxy'} = { %{$self->{'proxy'}} };
  937.     $copy->{'no_proxy'} = [ @{$self->{'no_proxy'}} ];  # copy array
  938.  
  939.     # remove reference to objects for now
  940.     delete $copy->{cookie_jar};
  941.     delete $copy->{conn_cache};
  942.  
  943.     $copy;
  944. }
  945.  
  946.  
  947.  
  948.  
  949. =item $ua->mirror($url, $file)
  950.  
  951. Get and store a document identified by a URL, using If-Modified-Since,
  952. and checking of the Content-Length.  Returns a reference to the
  953. response object.
  954.  
  955. =cut
  956.  
  957. sub mirror
  958. {
  959.     my($self, $url, $file) = @_;
  960.  
  961.     LWP::Debug::trace('()');
  962.     my $request = HTTP::Request->new('GET', $url);
  963.  
  964.     if (-e $file) {
  965.     my($mtime) = (stat($file))[9];
  966.     if($mtime) {
  967.         $request->header('If-Modified-Since' =>
  968.                  HTTP::Date::time2str($mtime));
  969.     }
  970.     }
  971.     my $tmpfile = "$file-$$";
  972.  
  973.     my $response = $self->request($request, $tmpfile);
  974.     if ($response->is_success) {
  975.  
  976.     my $file_length = (stat($tmpfile))[7];
  977.     my($content_length) = $response->header('Content-length');
  978.  
  979.     if (defined $content_length and $file_length < $content_length) {
  980.         unlink($tmpfile);
  981.         die "Transfer truncated: " .
  982.         "only $file_length out of $content_length bytes received\n";
  983.     } elsif (defined $content_length and $file_length > $content_length) {
  984.         unlink($tmpfile);
  985.         die "Content-length mismatch: " .
  986.         "expected $content_length bytes, got $file_length\n";
  987.     } else {
  988.         # OK
  989.         if (-e $file) {
  990.         # Some dosish systems fail to rename if the target exists
  991.         chmod 0777, $file;
  992.         unlink $file;
  993.         }
  994.         rename($tmpfile, $file) or
  995.         die "Cannot rename '$tmpfile' to '$file': $!\n";
  996.  
  997.         if (my $lm = $response->last_modified) {
  998.         # make sure the file has the same last modification time
  999.         utime $lm, $lm, $file;
  1000.         }
  1001.     }
  1002.     } else {
  1003.     unlink($tmpfile);
  1004.     }
  1005.     return $response;
  1006. }
  1007.  
  1008. =item $ua->proxy(...)
  1009.  
  1010. Set/retrieve proxy URL for a scheme:
  1011.  
  1012.  $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
  1013.  $ua->proxy('gopher', 'http://proxy.sn.no:8001/');
  1014.  
  1015. The first form specifies that the URL is to be used for proxying of
  1016. access methods listed in the list in the first method argument,
  1017. i.e. 'http' and 'ftp'.
  1018.  
  1019. The second form shows a shorthand form for specifying
  1020. proxy URL for a single access scheme.
  1021.  
  1022. =cut
  1023.  
  1024. sub proxy
  1025. {
  1026.     my $self = shift;
  1027.     my $key  = shift;
  1028.  
  1029.     LWP::Debug::trace("$key @_");
  1030.  
  1031.     return map $self->proxy($_, @_), @$key if ref $key;
  1032.  
  1033.     my $old = $self->{'proxy'}{$key};
  1034.     $self->{'proxy'}{$key} = shift if @_;
  1035.     return $old;
  1036. }
  1037.  
  1038. =item $ua->env_proxy()
  1039.  
  1040. Load proxy settings from *_proxy environment variables.  You might
  1041. specify proxies like this (sh-syntax):
  1042.  
  1043.   gopher_proxy=http://proxy.my.place/
  1044.   wais_proxy=http://proxy.my.place/
  1045.   no_proxy="localhost,my.domain"
  1046.   export gopher_proxy wais_proxy no_proxy
  1047.  
  1048. Csh or tcsh users should use the C<setenv> command to define these
  1049. environment variables.
  1050.  
  1051. On systems with case-insensitive environment variables there exists a
  1052. name clash between the CGI environment variables and the C<HTTP_PROXY>
  1053. environment variable normally picked up by env_proxy().  Because of
  1054. this C<HTTP_PROXY> is not honored for CGI scripts.  The
  1055. C<CGI_HTTP_PROXY> environment variable can be used instead.
  1056.  
  1057. =cut
  1058.  
  1059. sub env_proxy {
  1060.     my ($self) = @_;
  1061.     my($k,$v);
  1062.     while(($k, $v) = each %ENV) {
  1063.     if ($ENV{REQUEST_METHOD}) {
  1064.         # Need to be careful when called in the CGI environment, as
  1065.         # the HTTP_PROXY variable is under control of that other guy.
  1066.         next if $k =~ /^HTTP_/;
  1067.         $k = "HTTP_PROXY" if $k eq "CGI_HTTP_PROXY";
  1068.     }
  1069.     $k = lc($k);
  1070.     next unless $k =~ /^(.*)_proxy$/;
  1071.     $k = $1;
  1072.     if ($k eq 'no') {
  1073.         $self->no_proxy(split(/\s*,\s*/, $v));
  1074.     }
  1075.     else {
  1076.         $self->proxy($k, $v);
  1077.     }
  1078.     }
  1079. }
  1080.  
  1081. =item $ua->no_proxy($domain,...)
  1082.  
  1083. Do not proxy requests to the given domains.  Calling no_proxy without
  1084. any domains clears the list of domains. Eg:
  1085.  
  1086.  $ua->no_proxy('localhost', 'no', ...);
  1087.  
  1088. =cut
  1089.  
  1090. sub no_proxy {
  1091.     my($self, @no) = @_;
  1092.     if (@no) {
  1093.     push(@{ $self->{'no_proxy'} }, @no);
  1094.     }
  1095.     else {
  1096.     $self->{'no_proxy'} = [];
  1097.     }
  1098. }
  1099.  
  1100.  
  1101. # Private method which returns the URL of the Proxy configured for this
  1102. # URL, or undefined if none is configured.
  1103. sub _need_proxy
  1104. {
  1105.     my($self, $url) = @_;
  1106.     $url = $HTTP::URI_CLASS->new($url) unless ref $url;
  1107.  
  1108.     my $scheme = $url->scheme || return;
  1109.     if (my $proxy = $self->{'proxy'}{$scheme}) {
  1110.     if (@{ $self->{'no_proxy'} }) {
  1111.         if (my $host = eval { $url->host }) {
  1112.         for my $domain (@{ $self->{'no_proxy'} }) {
  1113.             if ($host =~ /\Q$domain\E$/) {
  1114.             LWP::Debug::trace("no_proxy configured");
  1115.             return;
  1116.             }
  1117.         }
  1118.         }
  1119.     }
  1120.     LWP::Debug::debug("Proxied to $proxy");
  1121.     return $HTTP::URI_CLASS->new($proxy);
  1122.     }
  1123.     LWP::Debug::debug('Not proxied');
  1124.     undef;
  1125. }
  1126.  
  1127. sub _new_response {
  1128.     my($request, $code, $message) = @_;
  1129.     my $response = HTTP::Response->new($code, $message);
  1130.     $response->request($request);
  1131.     $response->header("Client-Date" => HTTP::Date::time2str(time));
  1132.     return $response;
  1133. }
  1134.  
  1135. 1;
  1136.  
  1137. =back
  1138.  
  1139. =head1 SEE ALSO
  1140.  
  1141. See L<LWP> for a complete overview of libwww-perl5.  See F<lwp-request> and
  1142. F<lwp-mirror> for examples of usage.
  1143.  
  1144. =head1 COPYRIGHT
  1145.  
  1146. Copyright 1995-2001 Gisle Aas.
  1147.  
  1148. This library is free software; you can redistribute it and/or
  1149. modify it under the same terms as Perl itself.
  1150.  
  1151. =cut
  1152.  
  1153.  
  1154.